$(function () {
    var type_el = $('input.prior_type'),
        prior_type = type_el.val(), //1代表add 2代表edit
        data_start = type_el.attr('data-start'),
        img_src = type_el.attr('data-imgsrc'),
        time_start = type_el.attr('data-timestart'),
        time_end = type_el.attr('data-timeend');
    var time_cur = String(iService.CurentTime()).split(' ');
    if(prior_type==1){
        data_start = time_cur[0];
        time_start = time_cur[1].slice(0,5);
        time_end = iService.AddTimeUtil(new Date(),30).slice(0,5);
    }


    layui.use(['element', 'layer', 'form', 'laypage', 'laydate'], function () {
        var layer = layui.layer //获得layer模块
            , laypage = layui.laypage //获得laypage模块
            , laydate = layui.laydate //获得laydate模块
            , form = layui.form //获得laydate模块
            , element = layui.element;

        /*$('.btn-submit').on('click',function(){
            formSubmit();
        });*/

        /*var push_add = $('#member-push-add'),
            tel_add = $('.tel-input');

        push_add[0].onclick = function(){
            var tel_val = tel_add.val();
            var tel_reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则
            if(!tel_val){
                layer.msg('添加的手机号不能为空', {icon: 2,anim: 6,time:2*1000});
                return false;
            }else if(!tel_reg.test(tel_val)){
                layer.msg('手机号格式有误', {icon: 2,anim: 6,time:2*1000});
                return false;
            }
            var param = {
                url:'prior/addPhone',
                data:{
                    phone:tel_val
                }
            };

            $.JsonRpc(param,function(data){
                console.log(data);
                if(data.code==200){
                    $('<li class="active" data-pid="'+data.data.phone.pid+'">'+data.data.phone.phone+'</li>').prependTo('#staff-user-add');
                    checkStaff();
                }else {
                    layer.msg(data.data.message, {icon: 2,anim: 6,time:2*1000});
                }
            });
        };*/


        var pic_list = $('.pic-list'), upload_num = $('#upload-num');
        pic_list.on('click', '.pic-del', function () {
            $(this).parents('li').remove();
            upload_num.html(upload_num.html() - 1);
        });

        var btnSubmit = $('.btn-submit');

        form.on('submit(submit)', function (data) {
            if (btnSubmit.hasClass('false')) {
                layer.msg('课件尚未上传完，请稍后提交', {icon: 2, anim: 6, time: 2 * 1000});
                return false;
            }
            console.log(data.elem);//被执行事件的元素DOM对象，一般为button对象
            console.log(data.form); //被执行提交的form对象，一般在存在form标签时才会返回
            console.log(data.field); //当前容器的全部表单字段，名值对形式：{name: value}
            data.field.start_time += ':00';
            data.field.end_time += ':00';
            var form_field = data.field;
            form_field.notify = $('#staff-obj').attr('data-notify');
            form_field.phone = $('#staff-obj').attr('data-phone');
            form_field.bid = $('.pic-cd').attr('data-bid');

            var path = '', file = '';
            if (upload_num.html != 0) {
                var pic_li = $('.pic-list li');
                $.each(pic_li, function (e) {
                    path += $(this).attr('data-path') + ',';
                    file += $(this).attr('data-file') + ',';
                });
            }

            var pic_li_new = $('.pic-list li.new');
            var pic_li_old = $('.pic-list li.old');
            $.each(pic_li_old, function (e) {
                url.push($(this).attr('data-url'));
            });
            if (pic_li_new.length != 0) {
                $.each(pic_li_new, function (e) {
                    path += $(this).attr('data-path') + ',';
                    file += $(this).attr('data-file') + ',';
                });
            }



            form_field.path = path.slice(0, path.length - 1);
            form_field.file = file.slice(0, file.length - 1);
            console.log(form_field);
            formSubmit(form_field);
        });

        function formSubmit(form_field) {
            var param = {
                url: 'prior/addPost',
                data: form_field
            };
            $.JsonRpc(param, function (data) {
                console.log(data);
                if (data.code == 200) {
                    if (data.content.volume == 1) {
                        location.href = '/Question/add?llid=' + data.data.llid;
                    } else {
                        location.href = '/Prior/my';
                    }
                } else {
                    layer.msg(data.data.message, {icon: 2, anim: 6, time: 2 * 1000});
                }
            });
        }

        var staff_li = $('.staff-member-wrap li');

        function checkStaff() {
            var staffStr = '',
                staff_id = '',
                staff_add_Str = '',
                staff_add_id = '',
                staff_add_li = $('#staff-user-add li'),
                com_staff_li = $('#staff-company li');

            $.each(staff_add_li, function (e) {
                if ($(this).hasClass('active')) {
                    staff_add_Str += $(this).html() + '；&nbsp;&nbsp;';
                    staff_add_id += $(this).attr('data-pid') + ',';
                }
            });

            $.each(com_staff_li, function (e) {
                if ($(this).hasClass('active')) {
                    staffStr += $(this).html() + '；&nbsp;&nbsp;';
                    staff_id += $(this).attr('data-udid') + ',';
                }
            });
            staff_id = staff_id.slice(0, staff_id.length - 1);
            staff_add_id = staff_add_id.slice(0, staff_add_id.length - 1);
            var number = $('.staff-member-wrap li.active').length;
            if (number != 0) {
                $('input[name=number]').val(number);
            } else {
                $('input[name=number]').val('');
            }
            $('#staff-obj').html(staff_add_Str + staffStr).attr({
                'data-notify': staff_id,
                'data-phone': staff_add_id
            });
        }

        $('.staff-member-wrap').on('click', 'li', function () {
            $(this).toggleClass('active');
            checkStaff();
        });
        form.render(); //更新全部

        form.on('checkbox(s-checkbox)', function (data) {
//                console.log(data.elem); //得到checkbox原始DOM对象
//                console.log(data.elem.checked); //是否被选中，true或者false
//                console.log(data.value); //复选框value值，也可以通过data.elem.value得到
//                console.log(data.othis); //得到美化后的DOM对象
            if (data.elem.checked) {
                staff_li.addClass('active');
            } else {
                staff_li.removeClass('active');
            }
            checkStaff();
        });

        /*var start = {
            min: laydate.now()
            ,max: '2099-06-16 23:59:59'
            ,istime:true
            ,format: 'YYYY-MM-DD hh:mm:ss'
            ,istoday: false
            ,choose: function(datas){
            }
        };*/
        /*  document.getElementById('advance_time_start').onclick = function(){
           start.elem = this;
           laydate(start);
           };

           laydate.render({
           elem: '#advance_time_start' //指定元素
           ,trigger: 'click' //采用click弹出

           });
           */

        var insDate = laydate.render({
            elem: '#advance_date'
//                    ,theme: '#393D49'
            , value: data_start
            , min: String(iService.getNowFormatDate('-'))
        });

        var insStart = laydate.render({
            elem: '#advance_time_start'
//                ,theme: '#393D49'
            , value: time_start
            , type: 'time'
            , istime: true
            , format: 'HH:mm'

        });

        var insEnd = laydate.render({
            elem: '#advance_time_end'
//                ,theme: '#393D49'
            , value: time_end
            , type: 'time'
            , format: 'HH:mm'
        });

        /*var ins1 = laydate.render({
            elem: '#advance_time_start'
            ,type: 'datetime'
            ,trigger: 'click' //采用click弹出
            ,min:String(iService.getNowFormatDate('-'))

            /!*,change: function(value, date, endDate){
//                    ins1.hint(value); //在控件上弹出value值
                var ins2 = null;
                    ins2 = laydate.render({
                    elem: '#advance_time_end'
                    ,min: value
                    ,max: '2080-10-14'
                    ,ready: function(){
//                            ins2.hint('日期可选值设定在 <br> 2016-10-14 到 2080-10-14');
                    }
                });
            }*!/
            ,done: function(value, date, endDate) {
                console.log(value); //得到日期生成的值，如：2017-08-18
                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                var min = $.extend({},date);
                min.month = min.month-1;
                endIns.config.min = min;
                $(endIns.config.elem).focus().val('');

            }

        });


        var endIns = laydate.render({
            elem: '#advance_time_end'
            ,type: 'datetime'
            ,max: '2080-10-14'
            ,ready: function(){
//                            ins2.hint('日期可选值设定在 <br> 2016-10-14 到 2080-10-14');
            }


        })*/


        function bytesToSize(bytes) {
            if (bytes === 0) return '0 B';
            var k = 1000, // or 1024
                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                i = Math.floor(Math.log(bytes) / Math.log(k));

            return (bytes / Math.pow(k, i)).toPrecision(3) + '' + sizes[i];
        }

        //上传图片课件
        $('#upload_btn').off('change').on('change', function () {
            var file_arr = $("#upload_btn")[0].files;
            if (file_arr.length == 0) {
                //没有选择图片
                return false;
            }
            var img_arr = [];
            var pattern = /\d+(?=\.)/;  //匹配序号
            for (var i = 0, le = file_arr.length; i < le; i++) {
                if (le > 20) {
                    layer.msg('每次最多上传20张，请重新选择', {icon: 2, anim: 6, time: 2 * 1000});
                    return false;
                }
                var name_eq = file_arr[i].name.match(pattern);
                if (!name_eq) {
                    layer.msg('图片名不规范，请修改名字后重新上传', {icon: 2, anim: 6, time: 2 * 1000});
                    return false;
                }
                img_arr.push({nameIndex: i, name: name_eq, size: file_arr[i].size});
            }

            function compare(propertyName) {
                return function (object1, object2) {
                    var value1 = object1[propertyName];
                    var value2 = object2[propertyName];
                    return value1 - value2;
                }
            }

            img_arr.sort(compare("name"));
            console.log(img_arr);
            var k = 0, img_le = img_arr.length;

            function uploadImg(k) {
                var file_form = new FormData();
                var img_name = file_arr[img_arr[k].nameIndex].name;
                var img_size = file_arr[img_arr[k].nameIndex].size;
                file_form.append('img', file_arr[img_arr[k].nameIndex]); //单独传一个图片

                $.ajax({
                    type: "post",
                    url: "/about/upload",
                    data: file_form,
                    processData: false,
                    contentType: false,
                    async: true,
                    datatype: "JSON",
                    success: function (obj) {
                        var data = $.parseJSON(obj);
                        if (data.code != 200) {
                            layer.msg(data.data.message, {icon: 2, anim: 6, time: 2 * 1000});
                            return false;
                        } else {
                            file_form = null;
                            upload_num.html(parseInt(upload_num.html()) + 1);

                            $(
                                '<li class="new" data-path="' + data.data.path + '" data-file="' + data.data.file + '">' +
                                '<img src="'+img_src+data.data.path+data.data.file+'" alt="">' +
                                '<div class="info-card">' +
                                '<p class="ppt-name">' + img_name + '</p>' +
                                '<p><span class="pic-size">' + bytesToSize(img_size) + '</span> <i style="cursor: pointer;" class="pic-del">删除</i></p>' +
                                '</div>' +
                                '</li>'
                            ).appendTo(pic_list);

                            if (k < img_le - 1) {
                                k += 1;
                                setTimeout(function () {
                                    uploadImg(k);
                                }, 500);
                            } else {
//                                    图片全部上传完毕
                                btnSubmit.removeClass('false');
                                $('.layui-anim-loop').addClass('loopNone');
                            }
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest.readyState);
                        if (XMLHttpRequest.status == 413) {
                            console.log(XMLHttpRequest);
                        }
                        btnSubmit.removeClass('false');
                        $('.layui-anim-loop').addClass('loopNone');
                    }
                });
            }

            btnSubmit.addClass('false');
            $('.layui-anim-loop').removeClass('loopNone');
            uploadImg(k);
        });


        // 上传封面
        (function(){
            var pic_cbtn = $('.cover-choose');
            pic_cbtn.on('click', function () {
                var backdrop = $(this).attr('data-backdrop') ;
                backdrop = backdrop.slice(1,backdrop.length-1);
                backdrop = JSON.parse(backdrop);
                console.log(backdrop);

                var li_str = '';
                var pic_cover_el = $('.pic-cd');
                var bid_def = pic_cover_el.attr('data-bid');
                $.each(backdrop,function(e){
                    var li_class = '';
                    if(bid_def==backdrop[e].bid){
                        li_class = 'active';
                    }
                    li_str += '<li class="'+li_class+'" data-src="'+backdrop[e].image+'" data-status="'+backdrop[e].status+'" data-bid="'+backdrop[e].bid+'" ><img src="'+backdrop[e].image+'" alt=""> <i class="layui-icon">&#xe616;</i></li>';
                });
                layer.open({
                    type: 1,
                    title: '选择图片',
                    resize: false,
                    shadeClose: false,
                    close: false,
                    area: ['510px', '600px'],
                    content:
                    '<div id="pic-cover-pop" class="layui-tab">' +
                    '<ul class="layui-tab-title">' +
                    '<li class="layui-this">默认图库</li>' +
                    '<li>本地上传</li>' +
                    '</ul>' +
                    '<div class="layui-tab-content">' +
                    '<div class="layui-tab-item layui-show">' +
                    '<ul class="pic-cover-wrap clearfix">' +
                    li_str +
                    '</ul>' +
                    '<div class="cover-btn-wrap clearfix" >' +
                    '<span class="fr layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</span>' +
                    '<span class="fr layui-btn layui-btn-normal btn-modify" style="margin-right: 10px;">确定</span>' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-tab-item">' +
                    '<a href="javascript:void(0);" id="choose_btn_wrap" class="ucb-wrap" style="float: left; "><i class="icon iconfont icon-lianjie"></i>选择图片' +
                    '<input id="choose_btn" class="ucb-input" multiple="multiple"  type="file" accept="image/jpg,image/jpeg,image/png">' +
                    '</a>' +
                    '<div class="pic-wrap">' +
                    '</div>' +
                    '<div class="cover-btn-wrap clearfix" >' +
                    '<span class="fr layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</span>' +
                    '<span class="fr layui-btn layui-btn-normal btn-modify" style="margin-right: 10px;">确定</span>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>',
                    success: function (layero, index) {
                        var btn_modify_el = $('#live-pw-wrap .btn-modify');
                        var li_el = $('.pic-cover-wrap li');
                        li_el.hover(function () {
                            if (!$(this).hasClass('active')) {
                                $(this).find('.layui-icon').stop().fadeIn();
                            }
                        }, function () {
                            if (!$(this).hasClass('active')) {
                                $(this).find('.layui-icon').hide();
                            }
                        });
                        li_el.on('click', function () {
                            $(this).addClass('active').siblings('li').removeClass('active').find('.layui-icon').hide();
                        });
                        $('.btn-modify').eq(0).on('click',function(){
                            var li_active = $('.pic-cover-wrap').children('li.active');
                            var bid_cur = li_active.attr('data-bid');
                            pic_cover_el.attr({'data-bid':bid_cur,'src':li_active.attr('data-src')});
                            layer.closeAll();
                        });
                        $('#choose_btn').off('change').on('change',function(){
                            var file_arr = $("#choose_btn")[0].files[0];

                            if (file_arr.length == 0) {
                                //没有选择图片
                                return false;
                            }
                            var file_form = new FormData();
                            file_form.append('img', file_arr);    //单独传一个图片

                            // var file_form = new FormData($('#user-pic-form')[0]); //提交表单所有数据

                            $.ajax({
                                type: "post",
                                url: "/about/upload",
                                data: file_form,
                                processData: false,
                                contentType: false,
                                async: true,
                                datatype: "JSON",
                                success: function (obj) {
                                    var data = $.parseJSON(obj);
                                    console.log(data);
                                    if (data.code != 200) {
                                        layer.msg(data.data.message, {icon: 2, anim: 6, time: 2 * 1000});
                                        return false;
                                    } else {
                                        file_form = null;
                                        $('.pic-wrap').html('<img data-path="'+data.data.path+'"  data-file="'+data.data.file+'"  src="'+img_src+data.data.path+data.data.file+'" alt="">');
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    console.log(XMLHttpRequest.readyState);
                                }
                            })
                        });

                        $('.btn-modify').eq(1).on('click',function(){
                            if($('.pic-wrap').html()!=''){
                                var img_local = $('.pic-wrap').children('img');

                                var param = {
                                    url:'Backdrop/add',
                                    data:{
                                        file:img_local.attr('data-file'),
                                        path:img_local.attr('data-path'),
                                        status:2
                                    }
                                };
                                function successFun(data){
                                    if(data.code==200){
                                        console.log(data);
                                        pic_cover_el.attr({'data-bid':data.data.bid,'src':img_local.attr('src')});
                                        layer.closeAll();
                                    }else {
                                        layer.msg(data.data.message, {icon: 2, anim: 6, time: 2 * 1000});
                                    }
                                }
                                $.JsonRpc(param,successFun);
                            }else {
                                layer.msg('请先选择图片！', {icon: 2, anim: 6, time: 2 * 1000});
                            }

                        });

                    }
                });
            });
            // pic_cbtn.trigger('click');
            pic_cbtn = null;
        })();

        //搜索员工并且添加
        (function(){
            function openSearchLayer(val_search) {
                layer.open({
                    type: 1,
                    title: '搜索员工',
                    resize: false,
                    shadeClose: false,
                    close: false,
                    area: ['520px', '600px'],
                    content:
                    '<div id="man-search-wrap" class="layui-tab">' +

                    '<form id="add_search_form" action="" class="clearfix" onsubmit="return false;">' +
                    '<input class="secrch_key fl" type="search" value="" maxlength="16" name="search" autocomplete="off" id="J_search" placeholder="搜索" value="">' +
                    '<input type="submit" class="submit fr" value="">' +
                    '</form>' +
                    '<ul class="man-list">' +
                    '<li class="clearfix">' +
                    '<span class="man-info">12134545 测试测试测试 哈哈</span>' +
                    '<i class="layui-icon fr">&#xe616;</i>' +
                    '</li>' +
                    '<li class="clearfix">' +
                    '<span class="man-info">12134545 测试测试测试 哈哈</span>' +
                    '<i class="layui-icon fr">&#xe616;</i>' +
                    '</li>' +
                    '</ul>' +
                    '<div class="cover-btn-wrap clearfix" style="margin-top: 6px;">' +
                    '<span class="fr layui-btn layui-btn-primary" onclick="layer.closeAll();">取消</span>' +
                    '<span class="fr layui-btn layui-btn-normal btn-modify" style="margin-right: 10px;">确定</span>' +
                    '</div>' +
                    '</div>',
                    success: function (layero, index) {
                        var btn_modify_el = $('#man-search-wrap .btn-modify');
                        var ul_el = $('.man-list');
                        ul_el.on('click', 'li', function () {
                            const i_el = $(this).find('i');
                            if (i_el.hasClass('active')) {
                                i_el.removeClass('active');
                            } else {
                                i_el.addClass('active');
                            }
                        });
                        ul_el = null;
                        const input_el = $('.secrch_key');
                        var req = null;
                        input_el.bind('input propertychange', function () {
                            var sear_keywords = $(this).val();
                            function search_req(param) {
                                var staff_choose = $('#staff-company li.active');
                                var staff_coose_array = [];
                                $.each(staff_choose, function (e) {
                                    staff_coose_array.push($(staff_choose[e]).attr('data-udid'));
                                });
                                var jquerAjax = $.ajax({
                                    type: "post",
                                    url: '/Prior/search',
                                    datatype: "JSON",
                                    data: {
                                        keywords: param
                                    },
                                    async: true,
                                    success: function (obj) {
                                        if (typeof(obj) == "object") {
                                            successFunc(obj);
                                            //    更新搜索出来的列表
                                        } else {
                                            try {
                                                //window.location.href = urll;
                                                var response = $.parseJSON(obj);
                                                var re_code = response.code;
                                                if (re_code == 300) {
                                                    //清除浏览器缓存数据 跳转登录页面，
                                                    /*$.cookie("delete", {
                                                        name: 'login'
                                                    });
                                                    var login_flag = $.cookie("exist", {
                                                        name: 'login_flag'
                                                    });
                                                    if(login_flag){
                                                        $.cookie("delete", {
                                                            name: 'login_flag'
                                                        });
                                                    }
                                                    localStorage.clear();*/
                                                    window.location.href = "../../view/index.html";
                                                    return false;
                                                } else if (re_code == 400) {
                                                    layer.msg(response.data.message, {
                                                        icon: 2,
                                                        anim: 6,
                                                        time: 2 * 1000
                                                    });
                                                } else if (re_code == 500) {
                                                    layer.msg('服务器错误，请刷新重试！', {icon: 2, anim: 6, time: 2 * 1000});
                                                    return false;
                                                } else if (re_code == 200) {
                                                    if (response.data.count > 0) {
                                                        var ul_list = response.data.lists;
                                                        var tpl = '<li class="clearfix title">' +
                                                            '<span class="man-sec">部门</span>' + '<span class="man-phone">手机</span>' + '<span class="man-nickname">昵称</span>' +
                                                            '</li>';

                                                        var flag = 1;
                                                        $.each(ul_list, function (e) {
                                                            if ($.inArray(String(ul_list[e].udid), staff_coose_array) < 0) {
                                                                flag = 2;
                                                                var man_sec = ul_list[e].section;
                                                                if (man_sec == '') {
                                                                    man_sec = '未填写';
                                                                }
                                                                tpl +=
                                                                    '<li class="clearfix item">' +
                                                                    '<span class="man-sec">' + man_sec + '</span>' +
                                                                    '<span class="man-phone">' + ul_list[e].phone + '</span>' +
                                                                    '<span class="man-nickname">' + ul_list[e].nickname + '</span>' +
                                                                    '<i data-udid = ' + ul_list[e].udid + ' class="layui-icon fr">&#xe616;</i>' +
                                                                    '</li>';
                                                            }
                                                        });
                                                        (flag == 1 ? tpl = '<li style="text-align: center; border: none; padding-top: 40px;" class="clearfix">没有搜索到相关信息</li>' : tpl);
                                                        $('.man-list').html(tpl);
                                                    } else {
                                                        $('.man-list').html(
                                                            '<li style="text-align: center; border: none; padding-top: 40px;" class="clearfix">没有搜索到相关信息</li>'
                                                        );
                                                    }
                                                }

                                            } catch (err) {
                                                console.log(err);
                                            }
                                        }
                                    },
                                    error: function (e) {
                                        console.log("error: " + e.statusText)
                                    }
                                });
                                return jquerAjax;
                            }

                            if (req != null) {
                                req.abort();
                                req = search_req(sear_keywords);


                            } else {
                                req = search_req(sear_keywords)
                            }
                        });
                        input_el.focus().val(val_search);
                        input_el.trigger('input');
                        input_el.trigger('propertychange');
                        btn_modify_el[0].onclick = function () {
                            var li_choosed = $('.man-list').find('.layui-icon.active');
                            var choosed_arr = [];
                            $.each(li_choosed, function (i) {
                                const udid = $(li_choosed[i]).attr('data-udid');
                                choosed_arr.push(udid);
                            });

                            var staff_li_el = $('#staff-company li');
                            $.each(staff_li_el, function (e) {
                                const udid = $(this).attr('data-udid');
                                if ($.inArray(String(udid), choosed_arr) >= 0) {
                                    $(staff_li_el[e]).addClass('active');
                                }
                            });
                            layer.closeAll();
                            checkStaff();
                        };


                    }
                });
            }
            var input_se_el = $('.ser-input');
            var ser_sub = $('#search_submit');
            input_se_el.bind('input propertychange', function () {
                if ($(this).val()) {
                    $(this).blur();
                    var val_search = $(this).val();
                    $(this).val('');
                    openSearchLayer(val_search);
                }
            });
            ser_sub.on('click', function () {
                var val_search = $('.ser-input').val();
                if (val_search) {
                    $(this).blur();
                    openSearchLayer(val_search);
                    $(this).val('');
                } else if (val_search == '') {
                    layer.msg('搜索内容不能为空！', {icon: 2, anim: 6, time: 2 * 1000});
                }
            });
            input_se_el = null;
            ser_sub = null;
        })();
    });
});